package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hxkcloud.patient.ActivityManager;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.alarm.Alarm;
import com.hxkcloud.patient.alarm.Alarms;
import com.hxkcloud.patient.beans.ArticleKindBean;
import com.hxkcloud.patient.beans.ConsultMsgShowBean;
import com.hxkcloud.patient.beans.ConsulteBeanList;
import com.hxkcloud.patient.beans.MonitorKindBean;
import com.hxkcloud.patient.beans.PatientRemindBean;
import com.hxkcloud.patient.beans.RemindDateListBean;
import com.hxkcloud.patient.beans.RemindTimeBean;
import com.hxkcloud.patient.beans.UserMsgBean;
import com.hxkcloud.patient.dborm.ArticleKindDao;
import com.hxkcloud.patient.dborm.MonitorKindDao;
import com.hxkcloud.patient.fragments.BaseFragment;
import com.hxkcloud.patient.fragments.ConsulteFragment;
import com.hxkcloud.patient.fragments.MonitorPatientFragment;
import com.hxkcloud.patient.fragments.PatientFragment;
import com.hxkcloud.patient.fragments.RemindFragment;
import com.hxkcloud.patient.fragments.UserDiscoverFragment;
import com.hxkcloud.patient.fragments.UserHomePageFragment;
import com.hxkcloud.patient.interfaces.IResponseNewMsgInfoListener;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BadgeUtil;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.SharedPreferenceUtil;
import com.hxkcloud.patient.views.MainViewPager;
import com.zhuge.analysis.stat.ZhugeSDK;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by william_sun on 2016-07-06.
 * Description:用户登录主页面
 */
public class UserFragmentActivity extends BaseFragmentActivity implements View.OnClickListener {
    public MainViewPager viewPager;
    public List<BaseFragment> fragments = new ArrayList<BaseFragment>();
    private LinearLayout ll_discover, ll_monitor, ll_remind, ll_mine ,ll_consulte;
    private ImageView iv_discover, iv_monitor, iv_remind, iv_mine;
    private TextView tv_discover, tv_monitor, tv_remind, tv_mine,tv_consulte;
    private ImageView iv_remindpoint;//提醒上的红点
    private FragmentManager fragmentManager;
    private int currIndex = 0;// 当前页卡编号
    private boolean getbasic = false;//是否需要获取文章类型，监测类型
    private List<ArticleKindBean> kinds_news;
    private List<ArticleKindBean> kinds_course;
    private RemindTimeBean remindTimeBean;

    private List<RemindDateListBean.RemindDateBean> remindDates;//判断当天是否有提醒
    private List<PatientRemindBean> reminds;//判断当天接下来有没有提醒

    //    private UserDiscoverFragment userDiscoverFragment;
    // private UserDiscoverFragment1 userDiscoverFragment1;//原来的
   private UserHomePageFragment userDiscoverFragment1;
    //    private Monitor1Fragment monitor1Fragment;
    private MonitorPatientFragment monitorPatientFragment;
    private RemindFragment remindFragment;
    private PatientFragment patientFragment;
    private ConsulteFragment consulteFragment;

    private boolean isMsg = false;//推送打开消息页
    private boolean isCourse = false;//推送打开课堂
    private TextView tv_consult_icon;//咨询小红点
    private ConsultMsgShowBean consultMsgShowBean;

    private String groups = "";
    private ConsulteBeanList consulteBeanList;

    public static UserFragmentActivity userFragmentActivity;

    private boolean isPaySuccess = false;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_MONITORKIND_SUCCESS:
                List<MonitorKindBean> kinds = (List<MonitorKindBean>) msg.obj;
                if (kinds != null && kinds.size() > 0) {
                    MonitorKindDao monitorKindDao = new MonitorKindDao(mContext);
                    monitorKindDao.setKind(kinds, loginInfo.getDepartmentId());
                }

                monitorPatientFragment.isMonitorReady();
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_SUCCESS0:
                kinds_news = (List<ArticleKindBean>) msg.obj;
                if (kinds_course != null) {
                    ArticleKindDao kindDao = new ArticleKindDao(mContext);
                    kindDao.setKind(kinds_news, kinds_course, loginInfo.getDepartmentId());
                }
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_SUCCESS1:
                kinds_course = (List<ArticleKindBean>) msg.obj;
                if (kinds_news != null) {
                    ArticleKindDao kindDao = new ArticleKindDao(mContext);
                    kindDao.setKind(kinds_news, kinds_course, loginInfo.getDepartmentId());
                }
                break;
            case MessageCode.NETWORKCODE_GETREMINDTIMELIST_SUCCESS:
                remindTimeBean = (RemindTimeBean) msg.obj;

                setRemindTime();
                break;
            case MessageCode.NETWORKCODE_PATIENTREMINDDATELIST_SUCCESS:
                remindDates = (List<RemindDateListBean.RemindDateBean>) msg.obj;
                if (remindDates != null && remindDates.size() > 0) {
                    judgeDayRemind();
                }
                break;
            case MessageCode.NETWORKCODE_PATIENTREMINDLIST_SUCCESS:
                reminds = (List<PatientRemindBean>) msg.obj;
                if (reminds != null && reminds.size() > 0) {
                    judgeTimeRemind();
                }
                break;
            case MessageCode.MSG_CHECKNEWMSG_HAVE:
             /*   patientFragment.showPoint(true);
                userDiscoverFragment1.showPoint(true);
                monitorPatientFragment.showPoint(true);
                remindFragment.showPoint(true);*/

                break;
            case MessageCode.MSG_CHECKNEWMSG_HAVENOT:
               /* patientFragment.showPoint(false);
                userDiscoverFragment1.showPoint(false);
                monitorPatientFragment.showPoint(false);
                remindFragment.showPoint(false);*/
                break;
            case MessageCode.MSG_FRAGMENTACTIVITYVERSIONUPDATE:
                popup_easynotice1.showAtLocation(viewPager, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(UserFragmentActivity.this);
                break;
            case MessageCode.NETWORKCODE_CHECKCONSULTMSG_SUCCESS:
                if (msg.obj!=null){
                    consultMsgShowBean = (ConsultMsgShowBean) msg.obj;
                    int count = consultMsgShowBean.getCount()+YjhApplication.getInstance().getMsgNum();
                    if (count>0){
                        tv_consult_icon.setVisibility(View.VISIBLE);
                        tv_consult_icon.setText(count+"");
//                        tv_msg_consult.setVisibility(View.VISIBLE);
//                        tv_msg_nurse.setVisibility(View.VISIBLE);
//                        tv_msg_consult.setText(count+"");
//                        tv_msg_nurse.setText(count+"");
                    }else {
                        tv_consult_icon.setVisibility(View.INVISIBLE);
//                        tv_msg_consult.setVisibility(View.INVISIBLE);
//                        tv_msg_nurse.setVisibility(View.INVISIBLE);
                    }
                }
                break;
            case MessageCode.NETWORKCODE_CHECKCONSULTMSG_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datagetfail);
                }
                break;

            case MessageCode.NETWORKCODE_USERCOUNT_SUCCESS:
                if (msg.obj!=null){
                    consulteBeanList = (ConsulteBeanList) msg.obj;
                    if(consulteBeanList!=null){
                        groups = consulteBeanList.getJobGroup().get(0).getGroup();

                        if (!TextUtils.isEmpty(groups)){
                            viewPager.setSlipping(true);//设置ViewPager是否可以滑动
                        }else {
                            viewPager.setSlipping(false);//设置ViewPager是否可以滑动
                        }
                    }
                }
                break;
            case MessageCode.NETWORKCODE_USERCOUNT_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datagetfail);
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usermain);
        Log.i("---DDD->","onCreate");
        if (getIntent().hasExtra("page")) {
            currIndex = getIntent().getIntExtra("page", 0);
        }

        if(getIntent().hasExtra("isPaySuccess"))
        {
            isPaySuccess = getIntent().getBooleanExtra("isPaySuccess",false);
        }



        getbasic = getIntent().getBooleanExtra("getbasic", false);

        isMsg = getIntent().getBooleanExtra("msg", false);
        isCourse = getIntent().getBooleanExtra("course", false);

        initViews();

        if (getbasic) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    YiJiaHuNetWorkUtils.getMonitorKind(loginInfo.getDepartmentId(), handler);
                    YiJiaHuNetWorkUtils.articleKindList(loginInfo.getDepartmentId(), YjhApplication.articlekind_news, handler);//type两个都取|加入科室后重取
                    YiJiaHuNetWorkUtils.articleKindList(loginInfo.getDepartmentId(), YjhApplication.articlekind_course, handler);
                }
            }, 200);
        } else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    monitorPatientFragment.isMonitorReady();
                }
            }, 300);

        }
        if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
            YiJiaHuNetWorkUtils.getRemindTimeList(handler);
            YiJiaHuNetWorkUtils.getRemindDateList(handler);
        }
        getNewMsg();

        if (isMsg) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent iM = new Intent(mContext, MessageMainActivity.class);
                    startActivity(iM);
                }
            }, 500);
        } else if (isCourse) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Intent courseIntent = new Intent(mContext, NewsActivity.class);
                    courseIntent.putExtra("type", YjhApplication.articlekind_course);
                    startActivity(courseIntent);
                }
            }, 500);
        } else {
            // judgeUpdate();
        }

        userFragmentActivity = this;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Message msg = handler.obtainMessage(MessageCode.MSG_CHECKNEWMSG);
        msg.sendToTarget();
        if(isPaySuccess)
        {
            viewPager.setCurrentItem(2);
            isPaySuccess = false;
        }
        if (getIntent().hasExtra("alarm")){
            if ("alarm".equals(getIntent().getStringExtra("alarm"))){
                viewPager.setCurrentItem(3);
            }
        }
        checkNurseNewMsg();
        YiJiaHuNetWorkUtils.UserCount(loginInfo.getUserId(),handler);
        YiJiaHuNetWorkUtils.checkConsultNewMsg(loginInfo.getUserId(),handler);
    }


    @Override
    public void checkNurseNewMsg() {
        YiJiaHuNetWorkUtils.checkNurseNewMsg(new IResponseNewMsgInfoListener() {
            @Override
            public void responseInfo(Object object) {
                int num=0;
                if (object!=null){
                    UserMsgBean nurseMsgBean = (UserMsgBean) object;
                    num =nurseMsgBean.getAssessPatient()+nurseMsgBean.getEvalution()+nurseMsgBean.getSystem();
                    if (num>0){
                        patientFragment.showPoint(true);
                        userDiscoverFragment1.showPoint(true);
                        consulteFragment.showPoint(true);
                        monitorPatientFragment.showPoint(true);
                        remindFragment.showPoint(true);
                        YiJiaHuNetWorkUtils.checkConsultNewMsg(loginInfo.getUserId(),handler);
                    }else {
                        patientFragment.showPoint(false);
                        userDiscoverFragment1.showPoint(false);
                        consulteFragment.showPoint(false);
                        monitorPatientFragment.showPoint(false);
                        remindFragment.showPoint(false);
                    }
                }
                num +=YjhApplication.getInstance().getMsgNum();
                BadgeUtil.setBadgeCount(UserFragmentActivity.this,num);
            }
        });
    }

    private void initViews() {
        viewPager = (MainViewPager) findViewById(R.id.viewPager_user);
        iv_monitor = (ImageView) findViewById(R.id.iv_usermain_monitor);
        iv_remind = (ImageView) findViewById(R.id.iv_usermain_remind);
        iv_discover = (ImageView) findViewById(R.id.iv_usermain_discover);
        iv_mine = (ImageView) findViewById(R.id.iv_usermain_mine);
        ll_monitor = (LinearLayout) findViewById(R.id.ll_usermain_monitor);
        ll_remind = (LinearLayout) findViewById(R.id.ll_usermain_remind);
        ll_discover = (LinearLayout) findViewById(R.id.ll_usermain_discover);
        ll_mine = (LinearLayout) findViewById(R.id.ll_usermain_mine);
        ll_consulte = (LinearLayout) findViewById(R.id.ll_usermain_consulte);
        tv_consulte = (TextView) findViewById(R.id.tv_usermain_consulte);
        tv_monitor = (TextView) findViewById(R.id.tv_usermain_monitor);
        tv_remind = (TextView) findViewById(R.id.tv_usermain_remind);
        tv_discover = (TextView) findViewById(R.id.tv_usermain_discover);
        tv_mine = (TextView) findViewById(R.id.tv_usermain_mine);
        iv_remindpoint = (ImageView) findViewById(R.id.iv_usermain_remindpoint);

        tv_consult_icon = (TextView) findViewById(R.id.consult_suermain_icon);
        userDiscoverFragment1 = new UserHomePageFragment();
        monitorPatientFragment = new MonitorPatientFragment();
        remindFragment = new RemindFragment();
        patientFragment = new PatientFragment();

        consulteFragment = new ConsulteFragment();

        userDiscoverFragment1.setDepartmentIdChangeListener(new UserDiscoverFragment.departmentIdChangeListener() {
            @Override
            public void onDepartmentIdChange() {
                getLoginInfo();
                YiJiaHuNetWorkUtils.getMonitorKind(loginInfo.getDepartmentId(), handler);
                YiJiaHuNetWorkUtils.articleKindList(loginInfo.getDepartmentId(), YjhApplication.articlekind_news, handler);//type两个都取|加入科室后重取
                YiJiaHuNetWorkUtils.articleKindList(loginInfo.getDepartmentId(), YjhApplication.articlekind_course, handler);

//                monitor1Fragment.onResume();

                patientFragment.setChankeShow();
            }
        });
        patientFragment.setDepartmentIdChangeListener(new PatientFragment.departmentIdChangeSListener() {
            @Override
            public void onDepartmentIdChange() {
                userDiscoverFragment1.setNewDepartment();
            }
        });

        fragments.add(userDiscoverFragment1);
        fragments.add(monitorPatientFragment);

        fragments.add(consulteFragment);

        fragments.add(remindFragment);
        fragments.add(patientFragment);

        fragmentManager = this.getSupportFragmentManager();

        //viewPager.setSlipping(true);//设置ViewPager是否可以滑动
        if (!TextUtils.isEmpty(groups)){
            viewPager.setSlipping(true);//设置ViewPager是否可以滑动
        }else {
            viewPager.setSlipping(false);//设置ViewPager是否可以滑动
        }
        viewPager.setOffscreenPageLimit(0);
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
        viewPager.setAdapter(new MyPagerAdapter());
        viewPager.setCurrentItem(currIndex);

        ll_discover.setOnClickListener(this);
        ll_monitor.setOnClickListener(this);
        ll_remind.setOnClickListener(this);
        ll_mine.setOnClickListener(this);
        ll_consulte.setOnClickListener(this);
        LinearLayout.LayoutParams lp_bottom1 = new LinearLayout.LayoutParams((screenWidth / 15) - 5, (screenWidth / 15) - 5);
        iv_discover.setLayoutParams(lp_bottom1);
        iv_monitor.setLayoutParams(lp_bottom1);
        iv_mine.setLayoutParams(lp_bottom1);
        RelativeLayout.LayoutParams lp_bottom2 = new RelativeLayout.LayoutParams((screenWidth / 15) - 5, (screenWidth / 15) - 5);
        lp_bottom2.addRule(RelativeLayout.CENTER_HORIZONTAL);
        iv_remind.setLayoutParams(lp_bottom2);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_usermain_discover:
                if (currIndex!=0) viewPager.setCurrentItem(0);
                break;
            case R.id.ll_usermain_monitor:
                if (currIndex!=1) viewPager.setCurrentItem(1);
                break;
            case R.id.ll_usermain_consulte:
                if (!TextUtils.isEmpty(groups)){
                    if (currIndex!=2) viewPager.setCurrentItem(2);
                }else {
                    toastMsg("您还未加入分组\n请先加入分组");
                }
                break;
            case R.id.ll_usermain_remind:
                if (currIndex!=3) viewPager.setCurrentItem(3);
                break;
            case R.id.ll_usermain_mine:
                if (currIndex!=4) viewPager.setCurrentItem(4);
                break;

//            case R.id.ll_usermain_remind:
//                if (currIndex!=2) viewPager.setCurrentItem(2);
//                break;
//            case R.id.ll_usermain_mine:
//                if (currIndex!=3) viewPager.setCurrentItem(3);
//                break;


        }
    }

    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            switch (position) {
                case 0:
                    iv_discover.setImageResource(R.drawable.tab_discover_pre);
                    iv_monitor.setImageResource(R.drawable.tab_monitoring);
                    iv_remind.setImageResource(R.drawable.tab_remind);
                    iv_mine.setImageResource(R.drawable.tab_my);
                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue_text));
                    tv_monitor.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_remind.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_consulte.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    break;
                case 1:
                    iv_discover.setImageResource(R.drawable.tab_discover);
                    iv_monitor.setImageResource(R.drawable.tab_monitoring_pre);
                    iv_remind.setImageResource(R.drawable.tab_remind);
                    iv_mine.setImageResource(R.drawable.tab_my);
                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_monitor.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue_text));
                    tv_remind.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));

                    tv_consulte.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    break;

                case 2:
                        iv_discover.setImageResource(R.drawable.tab_discover);
                        iv_monitor.setImageResource(R.drawable.tab_monitoring);
                        iv_remind.setImageResource(R.drawable.tab_remind);
                        iv_mine.setImageResource(R.drawable.tab_my);
                        tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                        tv_monitor.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                        tv_remind.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                        tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_consulte.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue_text));
                    break;
                case 3:
                    iv_discover.setImageResource(R.drawable.tab_discover);
                    iv_monitor.setImageResource(R.drawable.tab_monitoring);
                    iv_remind.setImageResource(R.drawable.tab_remind_pre);
                    iv_mine.setImageResource(R.drawable.tab_my);
                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_monitor.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_remind.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue_text));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_consulte.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    iv_remindpoint.setVisibility(View.GONE);
                    break;
                case 4:
                    iv_discover.setImageResource(R.drawable.tab_discover);
                    iv_monitor.setImageResource(R.drawable.tab_monitoring);
                    iv_remind.setImageResource(R.drawable.tab_remind);
                    iv_mine.setImageResource(R.drawable.tab_my_pre);
                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_monitor.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_remind.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue_text));
                    tv_consulte.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
                    break;
//                case 2:
//                    iv_discover.setImageResource(R.drawable.tab_discover);
//                    iv_monitor.setImageResource(R.drawable.tab_monitoring);
//                    iv_remind.setImageResource(R.drawable.tab_remind_pre);
//                    iv_mine.setImageResource(R.drawable.tab_my);
//                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
//                    tv_monitor.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
//                    tv_remind.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue_text));
//                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
//                    iv_remindpoint.setVisibility(View.GONE);
//                    break;
//                case 3:
//                    iv_discover.setImageResource(R.drawable.tab_discover);
//                    iv_monitor.setImageResource(R.drawable.tab_monitoring);
//                    iv_remind.setImageResource(R.drawable.tab_remind);
//                    iv_mine.setImageResource(R.drawable.tab_my_pre);
//                    tv_discover.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
//                    tv_monitor.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
//                    tv_remind.setTextColor(ContextCompat.getColor(mContext, R.color.grey_text1));
//                    tv_mine.setTextColor(ContextCompat.getColor(mContext, R.color.light_blue_text));
//                    break;

                default:
                    break;
            }
            currIndex = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    private class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

//        @Override
//        public void destroyItem(View container, int position, Object object) {
//            ((ViewPager) container).removeView(fragments.get(position).getView());
//        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            ((ViewPager) container).removeView(fragments.get(position).getView());
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = fragments.get(position);
            //fragment.setVisibleToUser(true);
            if (!fragment.isAdded()) { // 如果fragment还没有added
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.add(fragment, fragment.getClass().getSimpleName());
                ft.commit();
                /**
                 * 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
                 * 会在进程的主线程中,用异步的方式来执行。
                 * 如果想要立即执行这个等待中的操作,就要调用这个方法(只能在主线程中调用)。
                 * 要注意的是,所有的回调和相关的行为都会在这个调用中被执行完成,因此要仔细确认这个方法的调用位置。
                 */
                fragmentManager.executePendingTransactions();
            }

            if (fragment.getView().getParent() == null) {
                container.addView(fragment.getView()); // 为viewpager增加布局
            }
            return fragment.getView();
        }

    }

    private void judgeDayRemind() {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String curDay = format.format(c.getTime());
        for (RemindDateListBean.RemindDateBean d : remindDates) {
            String date = d.getDate().split(" ")[0];
            if (date.equals(curDay)) {
                //today have remind
                YiJiaHuNetWorkUtils.getRemindList(date, handler);
            }
        }
    }

    private void judgeTimeRemind() {
        Calendar c = Calendar.getInstance();
        Long now = c.getTime().getTime();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (PatientRemindBean remind : reminds) {
            Long time = (long) 0;
            try {
                SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                String curDay = format1.format(c.getTime());
                time = format.parse(curDay + " " + remind.getTime()).getTime();
            } catch (ParseException e) {
            }
            if (time > now) {
                iv_remindpoint.setVisibility(View.VISIBLE);
                return;
            }
        }
    }

    //alarm function
    private void delAlarms() {
//        Cursor mCursor;
//        mCursor = Alarms.getAlarmsCursor(this
//                .getContentResolver());
//        while (mCursor.moveToNext()) {
//            Alarm alarm2 = new Alarm(mCursor);
//            Alarms.deleteAlarm(this, alarm2.id);
//        }
        Log.i("--DDD-->","55555555555555");
        Alarms.clearAlarm(this);
    }

    private void setRemindTime() {
        setRemindTimeTask task = new setRemindTimeTask();
        task.execute();
    }

    private long saveAlarm(long date, long time, int mHour, int mMinutes) {
        Alarm alarm = new Alarm();
        alarm.enabled = true;
        alarm.hour = mHour;
        alarm.minutes = mMinutes;
        alarm.isDelay = false;
        alarm.date = date + "";
        alarm.time = time + "";

        long timee = 0;
        timee = Alarms.addAlarm(this, alarm);
        return timee;
    }

    private class setRemindTimeTask extends AsyncTask<Object, Object, Boolean> {
        @Override
        protected Boolean doInBackground(Object... params) {
            delAlarms();

            List<Long> times = new ArrayList<>();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            List<RemindTimeBean.rTime> rTimes = remindTimeBean.getRlist();
            List<RemindTimeBean.eTime> eTimes = remindTimeBean.getElist();
            List<RemindTimeBean.rTime> kTimes = remindTimeBean.getKlist();

            if(null != rTimes)
            {
                for (RemindTimeBean.rTime rTime : rTimes) {
                    for (String t : rTime.getTimeList()) {
                        String time = rTime.getRemindDate() + " " + t;
                        Long timeLong = (long) 0;
                        try {
                            timeLong = format.parse(time).getTime();
                        } catch (ParseException e) {
                        }
                        addTime(times, timeLong);
                    }
                }
            }

            if(null != kTimes)
            {
                for (RemindTimeBean.rTime rTime : kTimes) {
                    for (String t : rTime.getTimeList()) {
                        String time = rTime.getRemindDate() + " " + t;
                        Long timeLong = (long) 0;
                        try {
                            timeLong = format.parse(time).getTime();
                        } catch (ParseException e) {
                        }
                        addTime(times, timeLong);
                    }
                }
            }

            Calendar c = Calendar.getInstance();
            Long now = c.getTime().getTime();

            if(null != eTimes)
            {
                for (RemindTimeBean.eTime eTime : eTimes) {
                    for (String t : eTime.getTimeList()) {
                        String time = eTime.getEndDate() + " " + t;
                        Long timeLong = (long) 0;
                        try {
                            timeLong = format.parse(time).getTime();
                        } catch (ParseException e) {
                        }
                        for (long last = timeLong; last > now; last -= 24 * 60 * 60 * 1000) {
                            addTime(times, last);
                        }
                    }
                }
            }

            for (long time : times) {
                if (time<System.currentTimeMillis())
                    continue;
                Date d = new Date(time);
                Calendar cTime = Calendar.getInstance();
                cTime.setTime(d);
                int hour = cTime.get(Calendar.HOUR_OF_DAY);
                int minute = cTime.get(Calendar.MINUTE);
                saveAlarm(time, time, hour, minute);
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
//do noting
            }
        }
    }

    private void addTime(List<Long> times, long time) {
        if (!times.contains(time)) {
            if (times.size() == 0) {
                times.add(0, time);
                return;
            } else if (times.size() == 1) {
                if (times.get(0) > time) {
                    times.add(0, time);
                    return;
                } else {
                    times.add(1, time);
                    return;
                }
            } else {
                if (time < times.get(0)) {
                    times.add(0, time);
                    return;
                } else if (time > times.get(times.size() - 1)) {
                    times.add(times.size(), time);
                    return;
                }
                for (int i = 0; i < times.size() - 1; i++) {
                    long time1 = times.get(i);
                    long time2 = times.get(i + 1);
                    if (time > time1 && time < time2) {
                        times.add(i + 1, time);
                        return;
                    }
                }
            }
        }
    }

    private long exitTime = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
//                Toast.makeText(mContext, R.string.doubleback, Toast.LENGTH_LONG).show();
                toastMsg(R.string.doubleback);
                exitTime = System.currentTimeMillis();
            } else {
                cancelToast();
                SharedPreferenceUtil.setIsrunning(mContext, false);
//                MobclickAgent.onKillProcess(this);

                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {

                        finish();
                        ActivityManager.getInstance().removeAllActivity();
                        System.exit(0);
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }, 200);
//                finish();
//                System.exit(0);
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    public static UserFragmentActivity getInstance() {
        return userFragmentActivity;
    }

    /**
     * 当有新的推送的时候执行一下刷新操作
     */
    public void jpushNew() {
        handler.sendEmptyMessage(MessageCode.MSG_CHECKNEWMSG_HAVE);
        checkNurseNewMsg();
        YiJiaHuNetWorkUtils.UserCount(loginInfo.getUserId(),handler);
        YiJiaHuNetWorkUtils.checkConsultNewMsg(loginInfo.getUserId(),handler);
    }

    public void jpushRefreshRemind() {
        if (viewPager.getCurrentItem() != 2) {
            Calendar c = Calendar.getInstance();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String curDay = format.format(c.getTime());
            YiJiaHuNetWorkUtils.getRemindList(curDay, handler);
        }
        remindFragment.onRefresh(null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ZhugeSDK.getInstance().flush(getApplicationContext());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
       // consulteFragment.refresh();
//        Log.i("---DDD->","intent");
    }
}

